<template>
    <div id="cesiumContainer" ></div>
    <div id="hud" class="hud-container">
      <div v-for="(value, key) in hudData" :key="key" class="hud-item">
        <span class="hud-label">{{ key }}:</span>
        <span class="hud-value">{{ value }}</span>
      </div>
    </div>
  </template>
  
  <script setup>
  import * as Cesium from 'cesium';
  import { onMounted, onUnmounted, ref } from 'vue';
  
  // HUD显示数据响应式对象
  const hudData = ref({
    '当前速度': '0.000 km/s',
    '轨道高度': '0.0 km',
    '机动剩余': '0.00 m/s'
  });
  
  // 卫星实体引用
  const satelliteEntity = ref(null);
  // 轨道数据存储
  const trajectoryData = ref([]);
  // 轨道修正点数据示例
  const correctionsData = ref([
    { 
      time: 720878800,          // 修正操作时间戳（J2000时间）
      position: [116.39, 39.9, 500000], // 空间位置（经度,纬度,高度）
      deltaV: 10.5              // 速度增量（米/秒）
    },
    { time: 720880000, position: [126.39, 35.9, 520000], deltaV: 5.2 }
  ]);
  // 定义剩余推进剂
  const remainingDeltaV = ref(100.0);
  // 定义地面站数据
  const groundStations = ref([]);
  // 定义船只数据
  const ships = ref([]);
  
  // 在组件挂载时初始化Cesium
  onMounted(async () => {
    // 设置 Cesium 的访问令牌
    Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI4MTNlOWJkNy01NTU0LTQ3ZWQtYmM3Yi1mNGViODFhOGY3NzQiLCJpZCI6MjgwODczLCJpYXQiOjE3NDEwNzIwNTl9.v7K25kZiBHwarMikqFQEH-NROT27E4JjdsmpUULH4J0";
  
    // 创建Cesium查看器
    const viewer = new Cesium.Viewer('cesiumContainer', {
      // terrainProvider: Cesium.createWorldTerrain(),
      timeline: true,
      animation: true,
      shouldAnimate: true,
      baseLayerPicker: true,
      geocoder: false,
      homeButton: true,
      infoBox: true,
      sceneModePicker: true,
      selectionIndicator: true,
      navigationHelpButton: true
    });
  
    // 加载轨道数据
    await loadTrajectoryData();
  
    // 加载地面站数据
    await loadGroundStations();
  
    // 加载船舶数据
    await loadShipData();
  
    if (trajectoryData.value.length > 0) {
      // 设置时钟范围
      const startTime = Cesium.JulianDate.fromDate(new Date(2022, 10, 5)); // 2022-11-05
      const stopTime = Cesium.JulianDate.addSeconds(startTime, trajectoryData.value[trajectoryData.value.length - 1].time - trajectoryData.value[0].time, new Cesium.JulianDate());
  
      viewer.clock.startTime = startTime.clone();
      viewer.clock.stopTime = stopTime.clone();
      viewer.clock.currentTime = startTime.clone();
      viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP;
      viewer.clock.multiplier = 50; // 50倍速播放
      viewer.timeline.zoomTo(startTime, stopTime);
  
      // 创建卫星位置的SampledPositionProperty
      const position = new Cesium.SampledPositionProperty();
  
      // 添加所有位置采样点
      trajectoryData.value.forEach(point => {
        const time = Cesium.JulianDate.addSeconds(startTime, point.time - trajectoryData.value[0].time, new Cesium.JulianDate());
        const pos = new Cesium.Cartesian3(point.x, point.y, point.z);
        position.addSample(time, pos);
      });
  
      // 创建CZML数据用于轨道路径可视化
      const czmlData = generateCzmlFromTrajectory(trajectoryData.value, startTime);
      viewer.dataSources.add(Cesium.CzmlDataSource.load(czmlData));
  
      // 添加卫星实体
      satelliteEntity.value = viewer.entities.add({
        name: '卫星',
        position: position,
        orientation: new Cesium.VelocityOrientationProperty(position),
        model: {
          uri: './models/glb/satellite.glb', // 确保此路径正确
          scale: 5000,
          minimumPixelSize: 64
        },
        path: {
          resolution: 1,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.3,
            color: Cesium.Color.YELLOW
          }),
          width: 3,
          leadTime: 0,
          trailTime: 60 * 60 // 显示1小时的轨迹
        }
      });
  
      // 添加修正点标记
      addCorrectionMarkers(viewer, correctionsData.value, startTime);
  
      // 添加地面站
      addGroundStations(viewer, groundStations.value);
  
      // 添加船只
      addShips(viewer, ships.value);
  
      // 设置初始视角到第一艘船的位置
      if(ships.value.length > 0) {
        const firstShip = ships.value[0].trajectory[0];
        const shipPosition = Cesium.Cartesian3.fromDegrees(
          firstShip.longitude,
          firstShip.latitude,
          firstShip.height + 5000  // 提升观察高度
        );
        viewer.camera.flyTo({
          destination: shipPosition,
          orientation: {
            heading: Cesium.Math.toRadians(0), // 正北方向
            pitch: Cesium.Math.toRadians(-45), // 俯视角度
            roll: 0
          },
          duration: 0 // 立即跳转
        });
      }

      // 设置跟踪实体优先级（船舶优先）
      viewer.trackedEntity = ships.value.length > 0 
        ? viewer.entities.getById(ships.value[0].name) 
        : satelliteEntity.value;
  
      // 实时更新HUD数据
      viewer.clock.onTick.addEventListener(clock => {
        updateHudData(viewer, position, clock.currentTime);
      });
    }
  });
  
  // 在组件卸载时清理资源
  onUnmounted(() => {
    if (viewer) {
      viewer.destroy();
    }
  });
  
  // 加载轨道数据
  async function loadTrajectoryData() {
    try {
      // 从后端API获取轨道数据
      const response = await fetch('https://your-backend-api.com/trajectory-data');
      if (!response.ok) {
        throw new Error('HTTP error! status: ' + response.status);
      }
      const data = await response.json();
      trajectoryData.value = data;
      console.log(`成功加载了 ${data.length} 条轨道数据`);
    } catch (error) {
      console.error('加载轨道数据失败:', error);
    }
  }
  
  // // 加载地面站数据
  // async function loadGroundStations() {
  //   try {
  //     // 从本地开发服务器获取地面站数据
  //     const response = await fetch('http://localhost:8080/orbit-data');
  //     if (!response.ok) throw new Error(`HTTP错误! 状态码: ${response.status}`);
  //     const data = await response.json();
  //     groundStations.value = data;
  //     console.log(`成功加载${data.length}个地面站`);
  //   } catch (error) {
  //     console.error('地面站数据加载失败:', error);
  //   }
  // }
  
  // 添加地面站可视化
  function addGroundStations(viewer, stations) {
    stations.forEach(station => {
      // 将地理坐标转换为三维笛卡尔坐标
      const position = Cesium.Cartesian3.fromDegrees(
        station.longitude,   // 地面站经度
        station.latitude,    // 地面站纬度
        station.height || 0  // 地面站高度（默认0米）
      );
  
      // 创建圆柱体表示地面站
      viewer.entities.add({
        name: station.name,
        position: position,
        cylinder: {
          length: station.height || 0,  // 圆柱体高度
          topRadius: 5,               // 顶部半径
          bottomRadius: 5,            // 底部半径
          material: Cesium.Color.RED  // 材质颜色
        },
        // 地面站标签配置
        label: {
          text: station.name,
          font: '14px sans-serif',
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM
        }
      });
    });
  }
  
  // 添加船舶可视化
  // 加载船舶数据
  async function loadShipData() {
    try {
      // 示例船舶数据（开发环境使用）
      ships.value = [{
        name: '远洋号',
        trajectory: [{
          time: 1667635200000,
          longitude: 121.47,
          latitude: 31.23,
          height: 0
        },{
          time: 1667638800000,
          longitude: 122.12,
          latitude: 30.89,
          height: 0
        }]
      }];
      console.log('成功加载船舶数据:', ships.value);
    } catch (error) {
      console.error('船舶数据加载失败:', error);
    }
  }
  
  // 修改船舶模型路径为Cesium内置模型
  function addShips(viewer, ships) {
    ships.forEach(ship => {
      // 创建船舶轨迹位置属性
      const position = new Cesium.SampledPositionProperty();
      ship.trajectory.forEach(point => {
        // 转换时间戳和地理坐标
        const time = Cesium.JulianDate.fromDate(new Date(point.time));
        const pos = Cesium.Cartesian3.fromDegrees(
          point.longitude,
          point.latitude,
          point.height || 0
        );
        position.addSample(time, pos);
      });
  
      // 创建船舶实体
      viewer.entities.add({
        name: ship.name,
        position: position,
        model: {
          uri: Cesium.IonResource.fromAssetId(2436), // Cesium官方船只模型
          scale: 10,
          minimumPixelSize: 64
        },
        path: {
          width: 3,
          material: new Cesium.PolylineGlowMaterialProperty({
            glowPower: 0.3,
            color: Cesium.Color.BLUE
          })
        }
      });
    });
  }
  
  // 生成CZML轨道数据
  function generateCzmlFromTrajectory(data, startTime) {
    const czml = [{ 
      id: "document", 
      name: "卫星轨道", 
      version: "1.0" 
    }];
  
    // 构建位置时间序列
    const positions = [];
    data.forEach(point => {
      const time = Cesium.JulianDate.addSeconds(
        startTime, 
        point.time - data[0].time, 
        new Cesium.JulianDate()
      );
      positions.push(point.x, point.y, point.z);
    });
  
    // 添加轨道路径
    czml.push({
      id: "path",
      name: "卫星轨道路径",
      path: {
        material: { 
          solidColor: { 
            color: { rgba: [0, 255, 255, 255] } // 青色轨迹
          }
        },
        width: 2
      },
      position: {
        epoch: Cesium.JulianDate.toIso8601(startTime),
        cartesian: positions
      }
    });
  
    return czml;
  }
  
  // 更新HUD数据
  function updateHudData(viewer, position, currentTime) {
    // 获取当前卫星位置
    const currentPosition = position.getValue(currentTime);
    if (!currentPosition) return;
  
    // 计算瞬时速度
    const nextTime = Cesium.JulianDate.addSeconds(currentTime, 1, new Cesium.JulianDate());
    const nextPosition = position.getValue(nextTime);
  
    if (nextPosition) {
      // 计算速度（米/秒）
      const velocity = Cesium.Cartesian3.distance(currentPosition, nextPosition);
      // 转换到地理坐标获取高度
      const cartographic = Cesium.Cartographic.fromCartesian(currentPosition);
  
      // 更新响应式数据
      hudData.value = {
        '当前速度': `${(velocity / 1000).toFixed(3)} km/s`,
        '轨道高度': `${(cartographic.height / 1000).toFixed(1)} km`,
        '机动剩余': `${remainingDeltaV.value.toFixed(2)} m/s`
      };
    }
  }
  </script>
  
  <style scoped>
  .hud-container {
    position: absolute;
    top: 10px;
    right: 10px;
    background-color: rgba(0, 0, 0, 0.7);
    color: white;
    padding: 10px;
    border-radius: 5px;
    font-family: 'Arial', sans-serif;
    z-index: 1000;
  }
  
  .hud-item {
    margin: 5px 0;
  }
  
  .hud-label {
    font-weight: bold;
    margin-right: 5px;
  }
  
  .hud-value {
    color: #4caf50;
  }
  </style>
  